<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="input-search" type="text" placeholder="输入城市名或拼音">
    </div>
    <div  class="search-content" ref="searchBox" v-show="keyword">
      <ul>
        <li class="search-item" v-for="item in list" :key="item.id" @click="handCityClick(item.name)">{{item.name}}</li>
        <li class="search-item" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
  import Bscroll from 'better-scroll'
    export default {
        name: "Search",
        props:{
          cities:Object //接受数据
        },
        data () {
          return {
            keyword :'',//input里输入的关键字
            list:[], //空数组用来存储城市
            timer:null //定时器
          }
        },
      computed : {//计算属性
          hasNoData () {
            return !this.list.length
          }
      },
      methods : {
        handCityClick(city){
          this.$store.dispatch("changeCity",city)
          this.$router.push("/")
        }
      },
       watch : {
          keyword () {//监听关键字的变化
            if(this.timer){//函数节流 性能优化
              clearTimeout(this.timer);
            }
            if(!this.keyword){//判断是否为空
              this.list=[];
              return;
            }
            this.timer=setTimeout(()=>{
              const result=[];
              for(let i in this.cities){//遍历对象cities
                    this.cities[i].forEach((value)=>{//遍历对象中的数组
                      //如果能找到关键字
                      if(value.spell.indexOf(this.keyword)>-1 || value.name.indexOf(this.keyword)>-1){
                        result.push(value);
                      }
                    })
              }
              this.list=result;//存入数据
            },100)
          }
       },
       mounted(){//生命周期函数钩子
          this.scroll=new Bscroll(this.$refs.searchBox)
       }
    }
</script>
<style lang="stylus" scoped>
  .search{
    background-color:#00bcd4;
    height:.36rem
    padding:0 .1rem;
    .input-search{
      width:100%;
      box-sizing border-box
      height:.31rem;
      line-height .31rem
      border-radius:.06rem;
      padding:0 .1rem
      text-align center
      color:#666
    }
  }
  .search-content{
    overflow hidden
    position absolute
    top .8rem
    left 0
    bottom 0
    right 0
    z-index 1
    background-color gainsboro
    .search-item{
      line-height .28rem
      border-bottom .01rem solid #cacaca
      background-color white
      padding-left .1rem
    }
  }
</style>
